package com.atguigu.guli.service.edu.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.atguigu.guli.service.edu.entity.Subject;
import com.atguigu.guli.service.edu.entity.excel.ExcelSubjectData;
import com.atguigu.guli.service.edu.entity.vo.SubjectVo;
import com.atguigu.guli.service.edu.listener.ExcelSubjectDataListener;
import com.atguigu.guli.service.edu.mapper.SubjectMapper;
import com.atguigu.guli.service.edu.service.SubjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author Helen
 * @since 2021-06-30
 */
@Service
public class SubjectServiceImpl extends ServiceImpl<SubjectMapper, Subject> implements SubjectService {

    @Override
    public void batchImport(InputStream inputStream) {

//        String fileName = "E:\\GuiGuJava\\Maven\\alibaba-easyexcel\\excel\\01-simpleWrite-07.xlsx";
        // 这里默认读取第一个sheet
        EasyExcel.read(inputStream, ExcelSubjectData.class, new ExcelSubjectDataListener(baseMapper)).excelType(ExcelTypeEnum.XLS).sheet().doRead();
    }

    @Override
    public List<SubjectVo> nestedList() {
        //方法一
//        return baseMapper.selectNestedListByParentId("0");

        //方法二
        // 效率高 1个sql，嵌套数据借助map封装，避免使用递归
        ArrayList<SubjectVo> subjectVoArraylist = new ArrayList<>();

        //查寻所有数据
        List<SubjectVo> subjects = baseMapper.selectSubjectVoList();

        HashMap<String, SubjectVo> map = new HashMap<>();
        for (SubjectVo subject : subjects) {
            String id = subject.getId();
            map.put(id,subject);
        }

        for (SubjectVo sub : subjects) {
            String parentId = sub.getParentId();
            if ("0".equals(parentId)){
                //说明是顶级菜单节点，添加到subjectVoArrayList中
                subjectVoArraylist.add(sub);
            }else {
                SubjectVo subjectVo = map.get(parentId);
                subjectVo.getChildren().add(sub);
            }
        }

        return subjectVoArraylist;
    }
}
